package com.time.hellotime.components.login;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

import com.google.gson.Gson;
import com.time.hellotime.R;
import com.time.hellotime.app.AddressManager;
import com.time.hellotime.base.BaseActivity;
import com.time.hellotime.components.MainActivity;
import com.time.hellotime.servermodel.BasicBean;
import com.time.hellotime.servermodel.User;
import com.time.hellotime.utils.JpushUtils;
import com.time.hellotime.utils.NetWorkUtils;
import com.time.hellotime.utils.ToastUtils;
import com.time.hellotime.views.CodeView;
import com.time.hellotime.views.TelephoneView;
import com.time.hellotime.webserver.helper.WebServerManager;
import com.time.hellotime.webserver.request.BasicRequest;
import com.time.hellotime.webserver.request.requestsParamters.LoginParameters;
import com.yanzhenjie.nohttp.rest.Request;
import com.yanzhenjie.nohttp.rest.Response;

/**
 * Register - user
 * Created by Bing on 2017/10/27.
 * E-mail is tx16bing@163.com
 */

public class RegisterActivity extends BaseActivity {

    private static final String EXTRA_ENTER_TYPE = "extra_enter_type";
    private static final String EXTRA_THREE_TYPE = "extra_three_type";
    private static final String EXTRA_OPEN_ID = "extra_open_id";
    private static final String EXTRA_THREE_INFO_TYPE = "extra_three_info_type";

    private String loginType, openId, threeInfo;

    private TelephoneView telephoneView;
    private CodeView codeView;
    private Button btnRegister;
    private ImageView ivCheck;

    private boolean isCheck;

    private Request request;
    private static final int VERIFY_USER_WHAT = 11;
    private static final int BINDING_USER_WHAT = 12;
    private static final int USER_INFO_WHAT = 27;

    public static void start(Activity activity, int requestCode, String enterType) {
        Intent intent = new Intent(activity, RegisterActivity.class);
        intent.putExtra(EXTRA_ENTER_TYPE, enterType);
        activity.startActivityForResult(intent, requestCode);
    }

    public static void start(Activity activity, int requestCode, String enterType, String threeType, String openId, String info) {
        Intent intent = new Intent(activity, RegisterActivity.class);
        intent.putExtra(EXTRA_ENTER_TYPE, enterType);
        intent.putExtra(EXTRA_THREE_TYPE, threeType);
        intent.putExtra(EXTRA_OPEN_ID, openId);
        intent.putExtra(EXTRA_THREE_INFO_TYPE, info);
        activity.startActivityForResult(intent, requestCode);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        loginType = getIntent().getStringExtra(EXTRA_THREE_TYPE);
        openId = getIntent().getStringExtra(EXTRA_OPEN_ID);
        threeInfo = getIntent().getStringExtra(EXTRA_THREE_INFO_TYPE);

        assignViews();
    }

    private boolean isThree() {
        if (!TextUtils.equals(getString(R.string.register_normal), getIntent().getStringExtra(EXTRA_ENTER_TYPE))) {
            return true;
        }

        return false;
    }

    private void assignViews() {
        telephoneView = findView(R.id.ll_telephone);
        codeView = findView(R.id.ll_code);
        btnRegister = findView(R.id.btn_register);
        btnRegister.setText(isThree() ? getString(R.string.activity_login_title)
                : getString(R.string.activity_register_title));
        ivCheck = findView(R.id.iv_agree_register);

        btnRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!checkForm()) return;

                if (isThree()) {
                    bindRequest();
                } else {
                    registerRequest();
                }
            }
        });

        ivCheck.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ivCheck.setImageResource(isCheck ? R.drawable.iv_protocol_select_normal : R.drawable.iv_protocol_selected);
                isCheck = !isCheck;
            }
        });
    }

    private boolean checkForm() {
        boolean formIsValid = true;
        if (TextUtils.isEmpty(telephoneView.getAccount())) {
            ToastUtils.showShort(getString(R.string.please_input_telephone));
            formIsValid = false;
        } else if (TextUtils.isEmpty(codeView.getCode())) {
            ToastUtils.showShort(getString(R.string.please_input_code));
            formIsValid = false;
        } else if (!isCheck) {
            ToastUtils.showShort(getString(R.string.please_agree_protocol));
            formIsValid = false;
        }
        return formIsValid;
    }

    /**
     * 提交注册
     */
    private void registerRequest() {
        if (NetWorkUtils.isNetAvailable(this)) {
            request = new BasicRequest(AddressManager.getInstance().getAddress());
            LoginParameters parameters = new LoginParameters();
            parameters.setCommand(getString(R.string.command_registerPerson));
            parameters.setAccountName(telephoneView.getAccount());
            parameters.setCode(codeView.getCode());
            if (TextUtils.isEmpty(JpushUtils.getRegisterId(this))) {
                parameters.setJpushId(getString(R.string.zero));
            } else {
                parameters.setJpushId(JpushUtils.getRegisterId(this));
            }
            request.add(getString(R.string.command), parameters.getCommand());
            request.add(getString(R.string.platform), parameters.getPlatform());
            request.add(getString(R.string.data), new Gson().toJson(parameters));
            request.setCancelSign(toString());
            WebServerManager.getInstance().add(this, request, this, VERIFY_USER_WHAT,
                    true, true, true);
        } else {
            ToastUtils.showShort(getString(R.string.network_error));
        }
    }

    /**
     * 绑定手机号
     */
    private void bindRequest() {
        if (NetWorkUtils.isNetAvailable(this)) {
            request = new BasicRequest(AddressManager.getInstance().getAddress());
            LoginParameters parameters = new LoginParameters();
            parameters.setCommand(getString(R.string.command_bindingThirdpartyLogin));
            parameters.setTelephone(telephoneView.getAccount());
            parameters.setCode(codeView.getCode());
            parameters.setOpenId(openId);
            parameters.setLoginType(loginType);
            parameters.setThirdPartyInfo(threeInfo);
            if (TextUtils.isEmpty(JpushUtils.getRegisterId(this))) {
                parameters.setJpushId(getString(R.string.zero));
            } else {
                parameters.setJpushId(JpushUtils.getRegisterId(this));
            }
            request.add(getString(R.string.command), parameters.getCommand());
            request.add(getString(R.string.platform), parameters.getPlatform());
            request.add(getString(R.string.data), new Gson().toJson(parameters));
            request.setCancelSign(toString());
            WebServerManager.getInstance().add(this, request, this, BINDING_USER_WHAT,
                    true, true, true);
        } else {
            ToastUtils.showShort(getString(R.string.network_error));
        }
    }

    // 加载个人信息
    private void getUserInfo() {
        if (NetWorkUtils.isNetAvailable(this)) {
            request = new BasicRequest(AddressManager.getInstance().getAddress());
            LoginParameters parameters = new LoginParameters();
            parameters.setCommand(getString(R.string.command_getUserInfo));
            parameters.setUserId(application.getAccount());
            if (TextUtils.isEmpty(JpushUtils.getRegisterId(this))) {
                parameters.setJpushId(getString(R.string.zero));
            } else {
                parameters.setJpushId(JpushUtils.getRegisterId(this));
            }
            request.add(getString(R.string.command), parameters.getCommand());
            request.add(getString(R.string.platform), parameters.getPlatform());
            request.add(getString(R.string.data), new Gson().toJson(parameters));
            request.setCancelSign(toString());
            WebServerManager.getInstance().add(this, request, this, USER_INFO_WHAT,
                    true, true, true);
        } else {
            ToastUtils.showShort(getString(R.string.network_error));
        }
    }

    @Override
    public void onSucceed(int what, Response<BasicBean> response) {

        BasicBean basicBean = response.get();
        if (basicBean == null) return;

        if (basicBean.isSuccess()) {
            User user = basicBean.parseData(User.class);
            if (user == null) return;
            application.setAppInfo(user.getUserId(), telephoneView.getAccount(), true);

            if (what == VERIFY_USER_WHAT || what == BINDING_USER_WHAT) {
                getUserInfo();
            } else if (what == USER_INFO_WHAT) {
                mVMcreator.setUserViewModel(user);
                MainActivity.start(this);
                setResult(RESULT_OK);
                finish();
            }

        } else {
            ToastUtils.showShort(basicBean.getMsg());
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != telephoneView){
            telephoneView.removeCallback();
        }
    }
}
